package com.example.common.common.config.response;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@RestControllerAdvice
public class GlobalResponseWrapper implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        Class<?> returnTypeClass = returnType.getParameterType();

        return !Response.class.isAssignableFrom(returnTypeClass)
                && !SseEmitter.class.isAssignableFrom(returnTypeClass)
                && !String.class.isAssignableFrom(returnTypeClass)
                && !Void.class.equals(returnTypeClass)
                && !void.class.equals(returnTypeClass);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {

        if (body == null) {
            return null;
        }

        if (body instanceof SseEmitter
                || body instanceof org.springframework.core.io.Resource
                || body instanceof org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody) {
            return body;
        }

        if (body instanceof Response) {
            return body;
        }


        // 其他类型直接包装为 Response
        return Response.success(body);
    }
}